package cn.opencodes.framework.core.shiro;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.opencodes.framework.core.service.AlphaService;
import cn.opencodes.framework.core.utils.SpringUtils;
import cn.opencodes.framework.core.utils.WebUtils;
import cn.opencodes.framework.tools.vo.CoreConst;

/**
 * Token权限过滤器
 * @author HJ
 */
public class AuthcSecretFilter extends AccessControlFilter {
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	public static final String HEADER_APP_KEY = JwtTokenGen.HEADER_APP_KEY;
	public static final String HEADER_SECRET_KEY = JwtTokenGen.HEADER_SECRET_KEY;
	
	private AlphaService commonSev;
	

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
    	if (commonSev == null) {
    		commonSev = SpringUtils.getBean(AlphaService.class);
		}
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
    	logger.debug("拦截URL：{}", getPathWithinApplication(request));
    	//获取请求的AppKey
        String appKey = WebUtils.getRequestAppKey(request);
        if(StringUtils.isBlank(appKey)){
            WebUtils.write(response, CoreConst.HttpStatus.PARAM_BLANK.value(), HEADER_APP_KEY + "不能为空");
            return false;
        }
        //获取请求的AppSecret
        String appSecret = WebUtils.getRequestAppSecret(request);
        if(StringUtils.isBlank(appSecret)){
        	WebUtils.write(response, CoreConst.HttpStatus.PARAM_BLANK.value(), HEADER_SECRET_KEY + "不能为空");
            return false;
        }
        //缓存获取并校验appSecret合法性
        boolean yes = commonSev.checkAppKeyAndSecret(appKey, appSecret);
        if (!yes) {
        	WebUtils.write(response, CoreConst.HttpStatus.TOKEN_EXPIRED.value(), HEADER_SECRET_KEY + "已失效");
            return false;
		}
        return true;
    }

}
